<?php

namespace Flow\models;

use Phalcon\Di;
use Helpers\Main;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\SoftDelete;

class BaseModel extends Model
{

    /**
     * 初始化软删除
     *
     * @return bool
     *
     * create by ck 20160701
     */
    public function initialize()
    {
        $this->useDynamicUpdate(true);
        $this->keepSnapshots(false);
        $this->addBehavior(new SoftDelete(
            array(
                'field' => 'bDelete',
                'value' => 1,
            )
        ));
    }

    /**
     * 根据id字段及数组删除记录
     *
     * @param $idField
     * @param $idArr
     * @return bool
     *
     * create by ck 20170722
     */
    public static function deleteRecord($idField, $idArr)
    {
        if(!$idField || !$idArr || !is_string($idField)) return false;
        is_string($idArr) and $idArr = explode(',', $idArr);
        return self::find([
            'conditions' => "bDelete = 0 AND {$idField} IN ({idArr:array})",
            'bind'       => ['idArr' => $idArr]
        ])->delete();
    }

    /**
     * 创建前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20170316
     */
    public function beforeCreate()
    {
        $userId  = Main::getLoginUserInfo('userId');
        $time    = date('Y-m-d H:i:s');
        if(property_exists($this, 'bDelete')){
            $this->writeAttribute('bDelete', 0);
        }
        if(property_exists($this, 'tCreateDate')){
            $this->writeAttribute('tCreateDate', $time);
        }
        if(property_exists($this, 'iCreateUserId')){
            $this->writeAttribute('iCreateUserId', $userId);
        }
        if(property_exists($this, 'tLastModifyDate')){
            $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if(property_exists($this, 'iLastModifyUserId')){
            $this->writeAttribute('iLastModifyUserId', $userId);
        }
        return true;
    }

    /**
     * 更新前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20170316
     */
    public function beforeUpdate()
    {
        if(property_exists($this, 'tLastModifyDate')){
            $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if(property_exists($this, 'iLastModifyUserId')){
            $this->writeAttribute('iLastModifyUserId', Main::getLoginUserInfo('userId'));
        }
        return true;
    }

    /**
     * 删除前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20160701
     * modify by ck 20170224    判断方法更改 isset->property_exists
     */
    public function beforeDelete()
    {
        $this->beforeUpdate();
        return true;
    }

}